<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.orders_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="daterangeOrderTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['orders:orders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['orders:orders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['orders:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['orders:orders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="订单号" align="center" prop="number" show-overflow-tooltip width="200"/>-->
      <el-table-column label="订单号" align="center" prop="number" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span class="order-number" style="color:#0471fd;" @click="copyToClipboard(scope.row.number)">{{ scope.row.number }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单用户" align="center" prop="userId" width="75"/>
      <el-table-column label="用户名" align="center" prop="userName" width="100" />
      <el-table-column label="购买商品" align="center" prop="goodsName" width="150"/>
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.goodsImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品价格(元)" align="center" prop="goodsPrice" width="100"/>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.orders_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="付款时间" align="center" prop="checkoutTime" width="150">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.checkoutTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 10"
            size="mini"
            type="text"
            @click="handlePay(scope.row)"
          >支付订单</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['orders:orders:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['orders:orders:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改理疗订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择订单状态">
            <el-option
              v-for="dict in dict.type.orders_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择" clearable>
            <el-option
              clearable
              v-for="item in userList"
              :key="item.userId"
              :label="`${item.userName} (${item.userId})`"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="购买商品" prop="goodsId">
          <el-select v-model="form.goodsId" placeholder="请选择" clearable>
            <el-option
              clearable
              v-for="item in therapyList"
              :key="item.id"
              :label="`${item.name} (${item.id})`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 支付订单对话框 -->
    <el-dialog :title="title" :visible.sync="openPay" width="500px" append-to-body>
      <el-row>
        <el-col :span="8">
          <image-preview :src="form.goodsImage" :width="150" :height="150"/>
        </el-col>
        <el-col :span="10">
          <div align="center">
            <image-preview src="/profile/upload/1.png" :width="100" :height="100"/>
            <p style="color: #ef0f3e">扫码支付</p>
          </div>
        </el-col>
        <el-col :span="6">
          <div align="">
            <el-button type="success" icon="el-icon-check" plain @click="payFee">我已支付</el-button>
          </div>
        </el-col>
      </el-row>
      <div style="display: flex; justify-content: space-between;">
        <div>
          <p><strong>订单号：</strong>{{ form.number }}</p>
          <p><strong>商品：</strong>{{ form.goodsName }}</p>
          <p><strong>价格：</strong>{{ form.goodsPrice }}元</p>
          <p><strong>下单时间：</strong>{{ form.orderTime }}</p>
        </div>
        <div>
          <dict-tag :options="dict.type.orders_status" :value="form.status"/>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/orders/orders";
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelect } from "@/api/system/user";
import { listTherapy, getTherapy, delTherapy, addTherapy, updateTherapy } from "@/api/therapy/therapy";

export default {
  name: "Orders",
  dicts: ['orders_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 理疗订单表格数据
      ordersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层（新增修改）
      open: false,
      // 是否显示弹出层（支付）
      openPay: false,
      // 购买商品时间范围
      daterangeOrderTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        number: null,
        status: null,
        orderTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        status: [
          { required: true, message: "订单状态不能为空", trigger: "change" }
        ],
        userId: [
          { required: true, message: "下单用户不能为空", trigger: "blur" }
        ],
        goodsId: [
          { required: true, message: "购买商品不能为空", trigger: "blur" }
        ],
      },
      //用户列表
      userList: [],
      //理疗列表
      therapyList: []
    };
  },
  created() {
    this.getList();
    this.getUserList();
    this.getTherapyList();
  },
  methods: {
    /** 查询理疗订单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeOrderTime && '' != this.daterangeOrderTime) {
        this.queryParams.params["beginOrderTime"] = this.daterangeOrderTime[0];
        this.queryParams.params["endOrderTime"] = this.daterangeOrderTime[1];
      }
      listOrders(this.queryParams).then(response => {
        this.ordersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser( {
        pageNum: 1,
        pageSize: 100
      }).then(response => {
          this.userList = response.rows;
          this.loading = false;
        }
      );
    },
    /** 查询项目管理列表 */
    getTherapyList() {
      this.loading = true;
      listTherapy({
        pageNum: 1,
        pageSize: 100
      }).then(response => {
        this.therapyList = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openPay = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        number: null,
        status: null,
        userId: null,
        goodsId: null,
        orderTime: null,
        checkoutTime: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加理疗订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrders(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改理疗订单";
      });
    },
    /** 打开订单详细 */
    handlePay(row) {
      this.reset();
      const id = row.id || this.ids
      getOrders(id).then(response => {
        this.form = response.data;
        this.openPay = true;
        this.title = "订单详细";
      });
    },
    /** 付钱 */
    payFee(){
      this.form.status = 11;
      updateOrders(this.form).then(response => {
        this.$modal.msgSuccess("支付成功");
        this.openPay = false;
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除理疗订单编号为"' + ids + '"的数据项？').then(function() {
        return delOrders(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('orders/orders/export', {
        ...this.queryParams
      }, `orders_${new Date().getTime()}.xlsx`)
    },
    // 其他方法...
    copyToClipboard(text) {
      const tempInput = document.createElement("input");
      tempInput.style.position = "absolute";
      tempInput.style.left = "-1000px";
      tempInput.style.top = "-1000px";
      tempInput.value = text;
      document.body.appendChild(tempInput);
      tempInput.select();
      document.execCommand("copy");
      document.body.removeChild(tempInput);
      this.$message.success("订单号已复制到剪贴板");
    },
  }
};
</script>
